package cn.dkdoo.utils.config.rollbackData;

import cn.dkdoo.utils.config.transactionInfo.TransactionInfoAbstract;
import cn.dkdoo.utils.utils.DkdSpringUtils;
import cn.dkdoo.utils.zookeeper.client.ICuratorCrudRepository;
import cn.dkdoo.utils.zookeeper.client.TypeToken;
import cn.dkdoo.utils.zookeeper.client.impl.CuratorCrudRepositoryImpl;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Type;

/**
 * @author nicky
 * @date 2021/5/10 下午3:54
 */
public class SaveRollbackDataZookper extends SaveRollbackDataAbstract {
    private static final Logger logger = LoggerFactory.getLogger(SaveRollbackDataZookper.class);

    private ICuratorCrudRepository zkRepository;

    public SaveRollbackDataZookper(ICuratorCrudRepository zkRepository) {
        this.zkRepository = zkRepository;
    }

    public SaveRollbackDataZookper() {
        try {
            this.zkRepository = DkdSpringUtils.getBeanByClass(ICuratorCrudRepository.class);
            if (zkRepository == null) {
                zkRepository = new CuratorCrudRepositoryImpl();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public String getTraNoPath(String traNo) {
        return SaveRollbackDataAbstract.pathPre + traNo;
    }

    @Override
    public void doSave(String traNo, TransactionInfoAbstract info) {
        logger.debug("保存回滚数据：{}\n{}", getTraNoPath(traNo), JSONObject.toJSONString(info));
        zkRepository.setJson(getTraNoPath(traNo), info);
    }

    @Override
    public TransactionInfoAbstract doGet(String traNo) {
        final Type bindType = new TypeToken<TransactionInfoAbstract>() {
        }.getType();
        TransactionInfoAbstract res = null;
        try {
            res = (TransactionInfoAbstract) zkRepository.getBean(getTraNoPath(traNo), bindType);
            logger.debug("获取回滚数据：{}\n{}", getTraNoPath(traNo), JSONObject.toJSONString(res));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return res;
    }
}
